package com.learn.order.config;

import com.learn.order.service.OrderService;
import com.mate.cloud.cache.config.BaseRedisConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import javax.annotation.Resource;

/**
 * 使用RedisMessageListenerContainer来订阅Redis的键过期事件，并指定回调方法进行处理
 * @author:         MI
 * @email:          448341911@qq.com
 * @createTime:     2024/5/24 15:25
 * @updateUser:     MI
 * @updateTime:     2024/5/24 15:25
 * @updateRemark:   修改内容
 * @version:        v1.0
 */
@Configuration
public class RedisConfig extends BaseRedisConfig {

    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    @Resource
    private OrderService orderService;

    @Bean
    RedisMessageListenerContainer container() {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        // 订阅所有db的过期事件
        container.addMessageListener((message, pattern) -> {
            String expiredKey = message.toString();
            if (expiredKey.startsWith("order:")) {
                // 处理订单超时逻辑
                String orderId = expiredKey.split(":")[1];
                // 这里调用order服务类方法，处理订单超时逻辑
                 orderService.cancelOrder(orderId);
            }
        }, new PatternTopic("__keyevent@*__:expired"));
        return container;
    }
}
